﻿using LeafBrowser.ViewModels;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace LeafBrowser.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const string DefaultUrlForAddedTabs = "https://www.baidu.com";

        public ObservableCollection<BrowserTabViewModel> BrowserTabs { get; set; }
        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;

            BrowserTabs = new ObservableCollection<BrowserTabViewModel>();

            CommandBindings.Add(new CommandBinding(ApplicationCommands.New, OpenNewTab));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, CloseTab));
            //webView.NavigationStarting += WebView_NavigationStarting;
            //InitializeAsync();
        }

        private void CloseTab(object sender, ExecutedRoutedEventArgs e)
        {
            if (BrowserTabs.Count > 0)
            {
                //Obtain the original source element for this event
                var originalSource = (FrameworkElement)e.OriginalSource;

                BrowserTabViewModel browserViewModel;

                if (originalSource is MainWindow)
                {
                    browserViewModel = BrowserTabs[TabControl.SelectedIndex];
                    BrowserTabs.RemoveAt(TabControl.SelectedIndex);
                }
                else
                {
                    //Remove the matching DataContext from the BrowserTabs collection
                    browserViewModel = (BrowserTabViewModel)originalSource.DataContext;
                    BrowserTabs.Remove(browserViewModel);
                }
                browserViewModel.WebView.Dispose();

                //browserViewModel.WebBrowser.Dispose();
            }
        }

        private void OpenNewTab(object sender, ExecutedRoutedEventArgs e)
        {
            CreateNewTab();
            TabControl.SelectedIndex = TabControl.Items.Count - 1;
        }

        private void CreateNewTab(string url = DefaultUrlForAddedTabs, bool showSideBar = false)
        {
            BrowserTabs.Add(new BrowserTabViewModel(url) { ShowSidebar = showSideBar });
        }

        public void OpenNewTab(string url = DefaultUrlForAddedTabs)
        {
            CreateNewTab(url);
            TabControl.SelectedIndex = TabControl.Items.Count - 1;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            OpenNewTab();
        }

        ///// <summary>
        ///// 于代码通信
        ///// </summary>
        //async void InitializeAsync()
        //{
        //    await webView.EnsureCoreWebView2Async(null);
        //    webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;
        //    await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
        //    await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
        //}

        //private void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
        //{
        //    String uri = args.TryGetWebMessageAsString();
        //    addressBar.Text = uri;
        //    webView.CoreWebView2.PostWebMessageAsString(uri);
        //}

        ///// <summary>
        ///// 开始加载内容的的处理
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="args"></param>
        //private void WebView_NavigationStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs args)
        //{
        //    String uri = args.Uri;
        //    if (!uri.StartsWith("https://"))
        //    {
        //        //使用js的代码
        //        webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
        //        args.Cancel = true;
        //    }
        //}

        //private void ButtonGo_Click(object sender, RoutedEventArgs e)
        //{
        //    if (webView != null && webView.CoreWebView2 != null)
        //    {
        //        webView.CoreWebView2.Navigate(addressBar.Text);
        //    }
        //}
    }
}
